package com.example.demo.controller;

import com.example.demo.entity.Member;
import com.example.demo.mapper.MemberMapper;
import com.example.demo.utils.PagingResult;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/member") // 控制器的前缀地址
public class MemberController {
    @Autowired
    MemberMapper memberMapper;

    /**
     * 获取所有会员数据
     * @return 会员列表
     */
    @GetMapping("/all")
    public List<Member> getAll() {
        return memberMapper.findAll();
    }
    
    /**
     * 获取分页的会员数据
     * @param limit 每页数量
     * @param offset 偏移量
     * @return 分页结果
     */
    @GetMapping("/list")
    public PagingResult<Member> select(
            @RequestParam(required = false, name = "limit", defaultValue = "10") int limit,
            @RequestParam(required = false, name = "offset", defaultValue = "0") int offset,
            @RequestParam(required = false, name = "field") String field,
            @RequestParam(required = false, name = "code") String code
    ) {
        List<Member> memberList;
        int total;
        
        if (code != null && !code.isEmpty()) {
            // 如果有搜索条件，使用搜索查询
            memberList = memberMapper.findBySearch(field, code, offset, limit);
            total = memberMapper.countBySearch(field, code);
        } else {
            // 否则使用普通分页查询
            memberList = memberMapper.findByPage(offset, limit);
            total = memberMapper.count();
        }
        
        return new PagingResult<Member>(memberList, total);
    }

    /**
     * 根据ID获取会员
     * @param id 会员ID
     * @return 会员对象
     */
    @GetMapping("/{id}")
    public Member getById(@PathVariable("id") int id) {
        return memberMapper.findById(id);
    }

    /**
     * 添加会员
     * @param member 会员对象
     * @return 影响行数
     */
    @PostMapping("/add")
    public int add(@RequestBody Member member) {
        return memberMapper.insert(member);
    }

    /**
     * 更新会员
     * @param member 会员对象
     * @return 影响行数
     */
    @PutMapping("/update")
    public int update(@RequestBody Member member) {
        return memberMapper.update(member);
    }

    /**
     * 删除会员
     * @param id 会员ID
     * @return 影响行数
     */
    @DeleteMapping("/delete/{id}")
    public int delete(@PathVariable("id") int id) {
        return memberMapper.delete(id);
    }
    
    /**
     * 检查用户名是否存在
     * @param userNo 用户名
     * @return 检查结果
     */
    @GetMapping("/check-user-no")
    public java.util.Map<String, Boolean> checkUserNoExists(@RequestParam("userNo") String userNo) {
        Member member = memberMapper.findByUserNo(userNo);
        java.util.Map<String, Boolean> result = new java.util.HashMap<>();
        result.put("exists", member != null);
        return result;
    }
}